package main

import (
	"fmt"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/userop_web/global"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/userop_web/initialize"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/userop_web/utils"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/userop_web/utils/register/consul"
	myvalidator "gitee.com/DonHz/electronic-business-systems/mxshop-api/userop_web/validator"
	"github.com/gin-gonic/gin/binding"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	"github.com/satori/go.uuid"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	// 1. 初始化
	// logger
	initialize.InitLogger()
	// 配置文件
	initialize.InitConfig()
	// router
	r := initialize.Routers()
	// validator
	err := initialize.InitTrans("zh")
	if err != nil {
		zap.L().Panic("初始化翻译器失败...", zap.Error(err))
		panic(err)
	}
	// 初始化srv连接
	initialize.InitSrvConn()
	viper.AutomaticEnv()
	debug := viper.GetBool("MXSHOP_DEBUG")
	if !debug {
		port, err := utils.GetFreePort()
		if err == nil {
			global.ServerConfig.Port = port
		}
	}
	// 注册验证器
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("phone", myvalidator.ValidatePhone)
		_ = v.RegisterTranslation("phone", global.Trans, func(ut ut.Translator) error {
			return ut.Add("phone", "{0} 非法的手机号码!", true)
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("phone", fe.Field())
			return t
		})
	}
	// 服务注册
	registerClient := consul.NewRegistry(global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port)
	serviceId := fmt.Sprintf("%s", uuid.NewV4())
	err = registerClient.Register(global.ServerConfig.Host, global.ServerConfig.Port, global.ServerConfig.Name, global.ServerConfig.Tags, serviceId)
	if err != nil {
		zap.S().Panic("订单服务注册失败:", err.Error())
	}

	// 启动服务器
	zap.L().Debug("启动服务器...", zap.Int("端口", global.ServerConfig.Port))
	go func() {
		if err := r.Run(fmt.Sprintf(":%d", global.ServerConfig.Port)); err != nil {
			zap.L().Panic("服务器启动失败...", zap.Error(err))
			panic(err)
		}
	}()
	// 优雅退出
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	if err = registerClient.DeRegister(serviceId); err != nil {
		zap.L().Info("注销商品web失败...", zap.Error(err))
	} else {
		zap.L().Info("注销商品web成功...")
	}
}
